var app = getApp()
var ConstantData = require('../../common/constant_data.js')
var common = require("../../common/common.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    showPage: false,
    disabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options:', options)
    var that = this
    that.setData({
      cardnumber: options.card || '',
      ids: options.ids || '',
    })
    this.getInfomantion()
    let nophone = app.getUserLoginNoPhone();
    if (nophone == 1) {
      that.setData({
        btnState: true
      })
    } else {
      that.setData({
        btnState: false,
        phoneNumber: wx.getStorageSync('iphone')
      })
    }


  },
    // 如果用过没有登录 让用户授权登录
    getPhoneNumber: function (e) {
      console.log(e, 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee')
      var that = this;
      if (e.detail.errMsg.indexOf('user deny') != -1) {
        return;
      } else {
        wx.showLoading({
          title: '登录中...',
        });
        //解密数据并登录成功
        app.executeRequest(function (header) {
          wx.request({
            url: app.BASE_URL + '/lease/auth/wxPhoneAuthLogin',
            header: header,
            data: {
              iv: encodeURIComponent(e.detail.iv),
              encryptedData: encodeURIComponent(e.detail.encryptedData)
            },

            success: function (res) {
              getApp().hideLoading();
              console.log('getPhoneNumber--res', res);
              let netErr = app.handleRes(res, that);
              if (netErr) {
                return
              }
              if (res.data.result === 0) {
                //登录成功
                // that.setData({
                //   showdialog:true,
                //   title: '登录成功',
                // })
                var btt = that.data.phoneAuthBtt;
                wx.setStorageSync('nophone', '2');
                app.globalData.loginData.nophone = 2;
                wx.setStorageSync('iphone', res.data.phone)
                that.setData({
                  user_id: res.data.uid ? res.data.uid : '',
                  phoneAuthStatus: false,
                  phoneAuthBtt: ''
                })
                that.pay()

              } else if (res.data.result === 4) {
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: res.data.description,
                  success(res) {}
                })
              } else {
                that.setData({
                  phoneAuthStatus: true,
                  phoneAuthBtt: 'scan',
                  loading_show: false
                });
                that.setData({
                  showdialog: true,
                  title: '请先登录',
                })
              }
            },
            fail: function (err) {
              getApp().hideLoading();
            }
          });

        });
      }
    },
  getInfomantion() {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    if (that.data.ids) {
      app.executeRequest(function (header) {
        wx.request({
          url: app.BASE_URL + '/icardHospitaled/toCreateOrder',
          header: header,
          data: {
            ids: that.data.ids,
            cardNum: that.data.cardnumber
          },
          success: function (res) {
            getApp().hideLoading()
            console.log(res, '/icardHospitaled/toCreateOrder')
            if(res.data.data && res.data.data.isClkFreeCard){
              wx.showToast({
                title: '选择成功',
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '../../pkgBak/pages/closedSociety/closedSociety',
                })
              }, 2000);
            }else{
              that.setData({
                cardnumber: res.data.data.cardInfo.cardNumber ? res.data.data.cardInfo.cardNumber : '',
                address: res.data.data.cardInfo.address ? res.data.data.cardInfo.address : '',
                nursingName: res.data.data.cardInfo.nursingName ? res.data.data.cardInfo.nursingName : '',
                totalPayPrice: res.data.data.totalPayPrice ? res.data.data.totalPayPrice : '',
                cardPayDeposit: res.data.data.cardPayDeposit ? res.data.data.cardPayDeposit : '',
                dataList: res.data.data.selEquipments ? res.data.data.selEquipments : '',
                showPage: true
              })
            }
            console.log(res, 'res.data.result')
            getApp().hideLoading();
          },
          fail: function (err) {
            that.setData({
              showdialog: true,
              title: '该订单已失效！',
            })
            getApp().hideLoading();
          }
        });

      });
    } else {

    }
  },
  pay() {
    var that = this
    that.setData({
      disabled: true
    })
    wx.showLoading({
      title: '请求中',
    })
    app.executeRequest(function (header) {
      wx.request({
        url: app.BASE_URL + '/icardHospitaled/toPayDeposit',
        header: header,
        data: {
          ids: that.data.ids,
          cardNum: that.data.cardnumber
        },
        success: function (res) {
          getApp().hideLoading()
          that.setData({
            disabled: false
          })
          console.log(res, '获取订单号')
          if (res.data.result == 0) {
            if(!res.data.data.wxPayParams){
              console.log('0元，不走收银台')
              wx.navigateTo({
                url: '../paySuccess/paySuccess?cardnumber=' + that.data.cardnumber + '&totalPayPrice=' + that.data.totalPayPrice,
              })
            }else{
            console.log(res.data.data.wxPayParams.data, '获取订单号')
            var data = res.data.data.wxPayParams.data
              wx.requestPayment({
                appId: 'wx0e458dc331e557cc',
                timeStamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.signType,
                paySign: data.paySign,
                success: function (res) {
                  console.log(res, '支付成功')
                  wx.navigateTo({
                    url: '../paySuccess/paySuccess?cardnumber=' + that.data.cardnumber + '&totalPayPrice=' + that.data.totalPayPrice,
                  })
                  // that.setData({
                  //   callServiceBoxStatus: false
                  // })
                // wx.getConnectedBluetoothDevices({
                //   services: ['FEE7'],
                //   success: function (res) {
                //     console.log("111----current connected blue " + JSON.stringify(res))
                //   },
                //   fail: function () {}
                // })
                },
                fail: function (res) { // 支付失败
                  that.setData({
                  showdialog: true,
                    title: '该订单已失效！',
                  })
                  common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'payD-' + JSON.stringify(res) : '');
                },
              complete: function (res) {}
              })
            }
          } else if (res.data.result == -1) {
            console.log('请求失败')
          } else {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: res.data.description,
              success(res) {}
            })
          }
          console.log('sadas dasd as das d')

        },
        fail(err) {
          that.setData({
            showdialog: true,
            title: 'error！',
          })
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})